<script setup>
import { Panel, useVueFlow } from '@vue-flow/core'

const flowKey = 'example-flow'

const { nodes, edges, addNodes, dimensions, toObject, fromObject } = useVueFlow()

function onSave() {
  localStorage.setItem(flowKey, JSON.stringify(toObject()))
}

function onRestore() {
  const flow = JSON.parse(localStorage.getItem(flowKey))

  if (flow) {
    fromObject(flow)
  }
}

function onAdd() {
  const id = nodes.value.length + 1

  const newNode = {
    id: `random_node-${id}`,
    label: `Node ${id}`,
    position: { x: Math.random() * dimensions.value.width, y: Math.random() * dimensions.value.height },
  }

  addNodes([newNode])
}

const isHidden = ref(false)

watch(isHidden, () => {
  nodes.value = nodes.value.map((node) => ({ ...node, hidden: isHidden.value }))
  edges.value = edges.value.map((edge) => ({ ...edge, hidden: isHidden.value }))
})
</script>

<template>
  <Panel position="top-right" class="save-restore-controls">
    <button style="background-color: #33a6b8" @click="onSave">保存</button>
    <button style="background-color: #113285" @click="onRestore">还原</button>
    <button style="background-color: #6f3381" @click="onAdd">新增节点</button>
    <button style="background-color: #6f3381" @click="isHidden = false">显示节点</button>
    <button style="background-color: #6f3381" @click="isHidden = true">隐藏节点</button>
  </Panel>
</template>

<style scoped>
/* 保存&还原 */
.save-restore-controls{
  font-size:12px;
  inset-block-start: 36px !important;
}

.save-restore-controls button{
  padding:5px;
  border-radius:5px;
  box-shadow:0 5px 10px 0 rgba(0,0,0,30%);
  box-shadow:0 5px 10px #0000004d;
  color:#fff;
  cursor:pointer;
  font-weight:700;
  margin-inline-start:5px;
  text-transform:uppercase
}

.save-restore-controls button:hover{
  transform:scale(105%);
  transition:.25s all ease-in-out
}

</style>
